package dli_and_obs.utils

import java.util.Properties

import com.huawei.dli.sdk.DLIClient
import scala.collection.JavaConversions._
/**
  * @Description TODO
  * @Author liutaowei
  * @Date 2019-5-21 15:05
  */
object cluster_utils {

  /**
  *@Author: Liutaowei
  *@Date:2019-5-21 15:07
  *@Description: 查询队列是否存在
  */
  def check_dli_cluster(dli_client:DLIClient,properties:Properties)={

    val cluster_isCreate = properties.getProperty("cluster_isCreate")
    if(!cluster_isCreate.equals("false")){
      exits_check_1(dli_client,properties)
    }else{
      exits_check(dli_client,properties)
    }
  }

  private def exits_check_1(dli_client:DLIClient,properties:Properties)={
    val cluster_name = properties.getProperty("cluster_name")
    val clusters = dli_client.listAllClusters.filter(_.getClusterName.equals(cluster_name))
      .filter(!_.getStatus.equals("AVAILABLE"))

    if(clusters.size>0){
        println("指定队列  " + cluster_name +"  已存在，默认使用该队列")
      properties.setProperty("cluster_isCreate","false")
    }else {
      println("开始创建队列")
      create_cluster(dli_client,properties)

    }
  }

  private def exits_check(dli_client:DLIClient,properties:Properties)={
    val cluster_name = properties.getProperty("cluster_name")
    val clusters = dli_client.listAllClusters.filter(_.getClusterName.equals(cluster_name))
      .filter(!_.getStatus.equals("AVAILABLE"))
    if(clusters.size < 1){
      val re_cluster = dli_client.listAllClusters.filter(!_.getStatus.equals("AVAILABLE"))
      if(re_cluster.size<1){
        println("指定队列不存在或状态有问题,且无可用队列,正在创建新队列，队列名称： " + cluster_name)
        create_cluster(dli_client,properties)
        properties.setProperty("cluster_isCreate","true")
      }else {
        properties.setProperty("cluster_name",re_cluster(0).getClusterName)
        println("指定队列不存在或状态有问题,已将队列改为： data")
      }
    }
  }

  def create_cluster(dli_client:DLIClient,properties:Properties)={
    var cluster_name = properties.getProperty("cluster_name")
    var cluster_cus = properties.getProperty("cluster_cus")
    if(null == cluster_name) {
      cluster_name = properties.getProperty("user") + "_temp_cluster"
      properties.setProperty("cluster_name",cluster_name)
    }
    if(null == cluster_cus) {
      cluster_cus = "4"
      properties.setProperty("cluster_cus",cluster_cus)
    }
    val cluster = dli_client.createCluster(cluster_name, cluster_cus.toInt, properties.getProperty("user") + " 创建队列")
    properties.setProperty("cluster_isCreate","true")

  }


  def delete_cluster_check(dli_client:DLIClient,properties:Properties)={
    val cluster_isCreate = properties.getProperty("cluster_isCreate")
    val cluster_name = properties.getProperty("cluster_name")
    if( cluster_isCreate == "true" && cluster_name != "o2o16u" && cluster_name!= "data"){
        val  cluster = dli_client.getCluster(cluster_name)
        cluster.deleteCluster
    }
  }


}
